package dashboardService

import (
	"fmt"
	"gitee.com/yangguoliang001/go-gin-vue3/config"
	"gitee.com/yangguoliang001/go-gin-vue3/pkg/response"
	"gitee.com/yangguoliang001/go-gin-vue3/util/code"
	"gitee.com/yangguoliang001/go-gin-vue3/vo"
	"github.com/gin-gonic/gin"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/host"
	"github.com/shirou/gopsutil/mem"
	"os"
	"runtime"
	"strconv"
	"strings"
	"time"
)

const (
	B  = 1
	KB = 1024 * B
	MB = 1024 * KB
	GB = 1024 * MB
)

func (d *dashboardService) QuerySystemInfo(c *gin.Context) (dashboardInfo vo.DashboardVo, err error) {
	// MySQL 版本数据
	mysqlVersion, err := d.dashboardDao.QueryMysqlVersion()
	fmt.Println("err", err)
	if err != nil {
		response.Fail(c, code.MySQLExecError, code.Text(code.MySQLConnectError), gin.H{"realErr": err})
		return
	}
	// redis 版本号
	server := d.cache.Info("server").Val()
	spl1 := strings.Split(server, "# Server")
	spl2 := strings.Split(spl1[1], "redis_version:")
	spl3 := strings.Split(spl2[1], "\r\nredis_git_sha1:")
	redisVersion := spl3[0]

	//
	memInfo, _ := mem.VirtualMemory()
	diskInfo, _ := disk.Usage("/")
	hostInfo, _ := host.Info()
	cpuInfo, _ := cpu.Info()
	cpuPercent, _ := cpu.Percent(time.Second, false)
	dir, _ := os.Getwd()
	//fmt.Println("memInfo", memInfo)
	//fmt.Println("diskInfo", diskInfo)
	//fmt.Println("hostInfo", hostInfo)
	//fmt.Println("cpuInfo", cpuInfo)
	//fmt.Println("cpuPercent", cpuPercent)

	var obj = new(vo.DashboardVo)
	obj.MemTotal = fmt.Sprintf("%d GB", memInfo.Total/GB)
	obj.MemUsed = fmt.Sprintf("%d GB", memInfo.Used/GB)
	obj.MemUsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", memInfo.UsedPercent), 64)

	obj.DiskTotal = fmt.Sprintf("%d GB", diskInfo.Total/GB)
	obj.DiskUsed = fmt.Sprintf("%d GB", diskInfo.Used/GB)
	obj.DiskUsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", diskInfo.UsedPercent), 64)

	obj.HostOS = fmt.Sprintf("%s(%s) %s", hostInfo.Platform, hostInfo.PlatformFamily, hostInfo.PlatformVersion)
	obj.HostName = hostInfo.Hostname

	if len(cpuInfo) > 0 {
		obj.CpuName = cpuInfo[0].ModelName
		obj.CpuCores = cpuInfo[0].Cores
	}
	if len(cpuPercent) > 0 {
		obj.CpuUsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", cpuPercent[0]), 64)
	}
	obj.GoPath = runtime.GOROOT()
	obj.GoVersion = runtime.Version()
	obj.Goroutine = runtime.NumGoroutine()
	obj.ProjectPath = strings.Replace(dir, "\\", "/", -1)
	obj.Host = "http://localhost://9988"
	obj.Env = "dev"
	obj.GoOS = runtime.GOOS
	obj.GoArch = runtime.GOARCH
	obj.ProjectVersion = config.ProjectVersion
	obj.MysqlVersion = mysqlVersion.MysqlVersion
	obj.RedisVersion = redisVersion
	return *obj, nil
}
